<template>
  <div class="p-4">
    <el-card>
      <!-- 搜索 & 新增 -->
      <div class="mb-4 flex justify-between items-center">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索学生姓名"
          clearable
          @keyup.enter="fetchStudents"
          style="width: 300px"
        />
        <el-button type="primary" @click="openForm()">新增学生</el-button>
      </div>

      <!-- 学生表格 -->
      <el-table
        :data="filteredStudents"
        border
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="130" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="className" label="班级" />
        <el-table-column prop="teacherName" label="教师姓名" />
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="sex" label="性别" width="80" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" @click="openForm(row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              :loading="deleteLoadingId === row.id"
              @click="handleDelete(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 弹窗 -->
      <el-dialog
        :title="form.id ? '编辑学生' : '新增学生'"
        v-model="formVisible"
        width="500px"
        @closed="resetForm"
      >
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
          <el-form-item label="教师姓名" prop="teacherName">
            <el-input v-model="form.teacherName" />
          </el-form-item>
          <el-form-item label="班级" prop="className">
            <el-input v-model="form.className" />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input-number v-model="form.age" :min="1" :max="150" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="formVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

import {
  getStudentList,
  addStudent,
  updateStudent,
  deleteStudent,
} from "../api/studentManage.js";


const loading = ref(false);
const deleteLoadingId = ref(null);

const formVisible = ref(false);
const formRef = ref(null);
const searchKeyword = ref("");
const students = ref([]);
const form = ref(getEmptyForm());


function getEmptyForm() {
  return {
    id: null,
    teacherId: null,
    teacherName: "",
    className: "",
    name: "",
    age: null,
    sex: "",
    email: "",
    createTime: "",
    updateTime: "",
  };
}

const rules = {
  teacherName: [{ required: true, message: "请输入教师姓名", trigger: "blur" }],
  className: [{ required: true, message: "请输入班级", trigger: "blur" }],
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  age: [{ required: true, message: "请输入年龄", trigger: "change" }],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
};

const filteredStudents = computed(() => {
  const keyword = searchKeyword.value.trim().toLowerCase();
  return keyword
    ? students.value.filter((s) => s.name?.toLowerCase().includes(keyword))
    : students.value;
});

function openForm(student = null) {
  form.value = student ? { ...student } : getEmptyForm();
  formVisible.value = true;
}

function resetForm() {
  form.value = getEmptyForm();
  formRef.value?.clearValidate();
}

async function fetchStudents() {
  loading.value = true;
  try {
    const res = await getStudentList();
    students.value = Array.isArray(res) ? res : res.data || [];
  } catch (err) {
    console.error("获取学生列表失败", err);
    ElMessage.error("获取学生列表失败");
  } finally {
    loading.value = false;
  }
}

async function handleSubmit() {
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      if (form.value.id) {
        await updateStudent(form.value);
        ElMessage.success("编辑成功");
      } else {
        await addStudent(form.value);
        ElMessage.success("新增成功");
      }
      formVisible.value = false;
      fetchStudents();
    } catch (err) {
      console.error("保存失败", err);
      ElMessage.error("保存失败");
    }
  });
}

async function handleDelete(id) {
  try {
    await ElMessageBox.confirm("确认删除该学生吗？", "提示", {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    });

    deleteLoadingId.value = id;
    await deleteStudent(id);

    students.value = students.value.filter((item) => item.id !== id);
    ElMessage.success("删除成功");
  } catch (err) {
    if (err !== "cancel") {
      console.error("删除失败", err);
      ElMessage.error("删除失败，请稍后重试");
    }
  } finally {
    deleteLoadingId.value = null;
  }
}

onMounted(fetchStudents);
</script>

<style scoped>
.p-4 {
  padding: 16px;
}
.mb-4 {
  margin-bottom: 16px;
}
.flex {
  display: flex;
}
.justify-between {
  justify-content: space-between;
}
.items-center {
  align-items: center;
}
</style>